package com.gdou.service.impl;

import com.gdou.commons.Result;
import com.gdou.mapper.SysNoticeMapper;
import com.gdou.model.SysNotice;
import com.gdou.service.SysNoticeService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.ServletRequestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SysNoticeServiceImpl implements SysNoticeService {

    @Autowired
    private SysNoticeMapper sysNoticeMapper;
    @Override
    public Result save(SysNotice sysNotice) {
        int rows = sysNoticeMapper.save(sysNotice);
        if (rows>0){
            return Result.SUCCESS;
        }else {
            return Result.DATA_FORMAT_ERROR;
        }

    }

    @Override
    public Result getById(Long id) {
       SysNotice notice= sysNoticeMapper.getById(id);
       if (notice==null){
           return Result.DATA_FORMAT_ERROR;
       }
        Result result = Result.SUCCESS;
        result.setData(notice);
        return result;
    }

    @Override
    public Result updateById(SysNotice sysNotice) {
        int rows = sysNoticeMapper.updateById(sysNotice);
        if (rows<1){
            return new Result(-1,"公告修改失败");
        }
        return Result.SUCCESS;
    }

    @Override
    public Result removeByIds(List<Long> list) {
       int rows= sysNoticeMapper.removeByIds(list);
       if(rows<1){
           return new Result(-1,"公告删除失败");
       }
        return Result.SUCCESS;
    }



    @Override
    public Result listNOtice(String title, HttpServletRequest request) {
        int current = ServletRequestUtils.getIntParameter(request,"current",1);
        int size = ServletRequestUtils.getIntParameter(request,"size",10);
        PageHelper.startPage(current, size);
        List<SysNotice> notices= sysNoticeMapper.selectAll();
        PageInfo<SysNotice> pageInfo = new PageInfo<>(notices);
        List<SysNotice> list = pageInfo.getList();
        List<SysNotice> listpage = list.stream().filter(notice -> notice.getTitle().contains(title)) // 应用筛选条件
                .collect(Collectors.toList());
        long total = pageInfo.getTotal();
        Result success = Result.SUCCESS;
        success.setData(listpage);
        success.setTotal(total);
        return success;
    }
}